import React, { Component } from 'react';
import { Keyboard, StyleSheet, View, TextInput, Text, TouchableHighlight, Platform } from 'react-native';
import PropTypes from "prop-types";
import Color from '../../config/theme/standard/color';

export default class Simplecode extends Component {
    constructor(props) {
        super(props);
        this.state = {
            text: this.props.defaultValue ? this.props.defaultValue : '',
            flag: this.props.autoFocus,
            prevText: this.props.defaultValue,
            prevAutoFocus: this.props.autoFocus
        };
        this.timer = null;
    }
    _onPress() {
        if (this.props.onPress) {
            this.props.onPress();
        } else {
            if (this.props.disable) {
                return;
            } else {
                this.setState({ flag: true },()=>{
                    this.textInputItem.focus();
                });
                //RN web下无法主动获取焦点，修改输入框为自动获取焦点并延迟主动获取焦点
                this.timer = setTimeout(() => {
                    if (this.state.flag) {
                        this.textInputItem.focus();
                    }
                }, 300);
            }
        }
    }

    clear() {
        this.setState({ text: '' });
    }



    componentDidMount() {
        this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this._keyboardDidHide.bind(this));
    }

    componentWillUnmount() {
        this.keyboardDidHideListener.remove();
        this.timer = null;
    }

    _keyboardDidHide() {
        if (this.state.flag) {
            this.textInputItem.blur();
        }
        this.setState({ flag: false })
    }

    _onChangeText(text) {
        
        this.setState({ text });
        if (this.props.onChangeText) {
            this.props.onChangeText(text);
        }
        if (text.length >= 6) {
            Keyboard.dismiss();
            this.setState({ flag: false });
            if (this.props.onEnd) {
                this.props.onEnd(text);
            }
        }

    }

    _onFocus() {
        if (this.props.onFocus) {
            this.props.onFocus();
        }
    }



    static getDerivedStateFromProps(nextProps, prevState) {
        let infoFlag = false;
        let valueFlag = false;
        if (('defaultValue' in nextProps) && (nextProps.defaultValue !== prevState.prevText)) {
            infoFlag = true;
        }
        if ('autoFocus' in nextProps && nextProps.autoFocus != prevState.prevAutoFocus) {
            valueFlag = true;
        }

        if (infoFlag && valueFlag) {
            return {
                text: nextProps.defaultValue,
                prevText: nextProps.defaultValue,
                flag: nextProps.autoFocus,
                prevAutoFocus: nextProps.autoFocus
            }
        }else{
            if (infoFlag) {
                return{
                    text: nextProps.defaultValue,
                    prevText: nextProps.defaultValue,
                }
            } else if(valueFlag){
                return {
                    flag: nextProps.autoFocus,
                    prevAutoFocus: nextProps.autoFocus
                }
            }
        }

        return null;
    }

    _getInputItem(){
        let inputItem = [];
        let text = this.state.text;
        let itemStyle = [styles.inputItem];

        if (this.props.disable) {
            itemStyle.push({ backgroundColor: Color.simplecode.disableBackground});
            text = '';
        } else {
            itemStyle.push({ backgroundColor: Color.white });
        }

        for (let i = 0; i < 6; i++) {
            if (i == 0) {
                inputItem.push(
                    <View key={i} style={itemStyle}>
                        {i < text.length ? <View style={[styles.iconStyle,{backgroundColor: this.props.disable ? Color.simplecode.disableIcon : Color.simplecode.icon}]}></View> : null}
                    </View>)
            }
            else {
                inputItem.push(
                    <View key={i} style={[itemStyle, styles.inputItemBorderLeftWidth]}>
                        {i < text.length ?
                            <View style={styles.iconStyle}>
                            </View> : null}
                    </View>)
            };
        }
        return inputItem;
    }

    render() {

        let { containerStyles, autoFocus, disable, defaultValue } = this.props;
        let { flag } = this.state;
        if (disable) {
            flag = false;
        }
        
        return (
            <TouchableHighlight onPress={() => this._onPress()} activeOpacity={1} underlayColor='transparent'>
                <View style={[styles.container, containerStyles]} >
                    {flag ?
                        <TextInput
                            ref={(obj) => this.textInputItem = obj}
                            style={{ width: 45 * 6 }}
                            maxLength={6}
                            autoFocus={true}
                            keyboardType="numeric"
                            underlineColorAndroid={"transparent"}
                            onFocus={() => this._onFocus()}
                            onChangeText={(text) => this._onChangeText(text)}
                            value={this.state.text}
                        /> :
                        <Text>{this.state.text}</Text>
                    }

                    <View style={[styles.inputCon, Platform.OS == 'harmony' &&{ zIndex:1 }]}>
                        {this._getInputItem()}
                    </View>
                </View>
            </TouchableHighlight>
        );
    }
}

Simplecode.propTypes = {
    containerStyles: PropTypes.object,
    autoFocus: PropTypes.bool,
    onChangeText: PropTypes.func,
    onEnd: PropTypes.func,
    onFocus: PropTypes.func,
    disable: PropTypes.bool,
    defaultValue: PropTypes.string,
    onPress: PropTypes.func,
}

Simplecode.defaultProps = {
    autoFocus: false,
    disable: false,
    defaultValue: ''
}

const styles = StyleSheet.create({
    container: {
        height: (Platform.OS === 'web') ? 47 : 46,
        width: (Platform.OS === 'web') ? (44 * 5 + 47) : (45 * 5 + 47),
        alignItems: 'center',
        flexDirection: 'row',   
        borderWidth: 1,
        borderColor: Color.simplecode.border,
        backgroundColor: Color.white,
        marginLeft: 10,
        marginTop: 10
    },
    inputCon: {
        flexDirection: 'row',
        position: 'absolute',
        justifyContent: 'flex-start',
        left: (Platform.OS === 'web') ? 1 : 0
    },
    inputItem: {
        height: 45,
        width: 45,
        justifyContent: 'center',
        alignItems: 'center',
       
    },
    inputItemBorderLeftWidth: {
        borderLeftWidth: 1,
        borderColor: Color.simplecode.border
    },
    iconStyle: {
        width: 13,
        height: 13,
        backgroundColor:Color.simplecode.icon,
        borderRadius: 7,
    },
});